use std::path::MAIN_SEPARATOR;

use anyhow::anyhow;
use salvo::{cors::Cors, prelude::StaticDir, Router};

use crate::{
    control::{
        login_control::{login, logout, user_tree_menu},
        menu_control::{add_menu, del_menu},
        org_control::{add_org, org_page},
        role_control::{add_role, del_role},
        user_control::{add_user, del_user, user_page},
        wx_callback_control::wx_call_back,
    },
    wechat::control::wechat_controller::{cursor, page},
};

use super::{app_config::CONFIG, handler_config::handler_auth};

pub struct MyRouter {}

impl MyRouter {
    pub fn route() -> anyhow::Result<Router> {
        let file_path = &CONFIG.server.file.path;
        let static_file_path = format!(
            "{}{}{}",
            std::env::current_dir()?
                .as_path()
                .to_str()
                .ok_or(anyhow!("current dir env error"))?,
            MAIN_SEPARATOR,
            file_path
        );
        let cors_handler = Cors::permissive().into_handler();
        let router = Router::with_hoop(cors_handler)
            .push(
                Router::with_path("<**path>")
                    .get(StaticDir::new([static_file_path]).auto_list(true)),
            )
            .push(Router::with_path("/login").post(login))
            .push(Router::with_path("callback").post(wx_call_back))
            .push(
                Router::new()
                    .hoop(handler_auth)
                    //.hoop(handler_permission)
                    .push(Router::with_path("/logout").post(logout))
                    .push(Router::with_path("/user/tree_menu").post(user_tree_menu))
                    .push(Router::with_path("/user/add_user").post(add_user))
                    .push(Router::with_path("/user/del_user").get(del_user))
                    .push(Router::with_path("/user/page_user").post(user_page))
                    .push(Router::with_path("/role/add_role").post(add_role))
                    .push(Router::with_path("/role/del_role").get(del_role))
                    .push(Router::with_path("/menu/add_menu").post(add_menu))
                    .push(Router::with_path("/menu/del_menu").get(del_menu))
                    .push(Router::with_path("/org/add_org").post(add_org))
                    .push(Router::with_path("/org/page_org").post(org_page))
                    .push(Router::with_path("/wechat_user/page").post(page))
                    .push(Router::with_path("/wechat_user/cursor").post(cursor)),
            );
        Ok(router)
    }
}
